﻿using Abp.Application.Services.Dto;
using Abp.Web.Models;
using Batman.Cms.Core.Controllers;
using Batman.Jianbei.Forum.Controllers.Dicts.Filters;
using Batman.Jianbei.Forum.Controllers.Dicts.PartitionInputs;
using Batman.Jianbei.Forum.Controllers.Dicts.TopicInput;
using Batman.Jianbei.Forum.Core.Domains.Dicts;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Omu.ValueInjecter;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Batman.Jianbei.Forum.Controllers.Dicts
{
    public class TopicController : BatmanController<Topic>
    {
        /// <summary>
        /// 分页数据
        /// </summary>
        /// <param name="page"></param>
        /// <returns></returns>
        public async Task<ActionResult> Page(PagedResultRequestDto page, TopicFilter filter)
        {
            var result = await Reader.GetPageAsync(page, query =>
            {
                if (filter.IsDeleted.HasValue)
                {
                    query = query.Where(t => t.IsDeleted == filter.IsDeleted.Value);
                }
                if (filter.IsOnline.HasValue)
                {
                    query = query.Where(t => t.IsOnline == filter.IsOnline.Value);
                }
                if (!string.IsNullOrEmpty(filter.Name))
                {
                    query = query.Where(t => t.Name.Contains(filter.Name));
                }
                if (!string.IsNullOrEmpty(filter.PartitionId))
                {
                    query = query.Where(t => t.PartitionId == filter.PartitionId);
                }
                query = query.OrderByDescending(t => t.Sort).ThenByDescending(t => t.CreateAt).AsQueryable();
                return query;
            });

            return Json(result);
        }

        /// <summary>
        /// 创建
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public ActionResult Create(TopicCreateInput model)
        {
            var result = BaseManager.Excute(repository =>
             {
                 var isExists = repository.GetAll().AsNoTracking().Where(t => t.Name == model.Name).Any();

                 if (isExists)
                 {
                     return new AjaxResponse { Success = false, Error = new ErrorInfo($"话题已存在:{model.Name}") };
                 }

                 var entity = ObjectMapper.Map<Topic>(model);
                 entity.CreateAt = DateTime.Now;
                 var insertResult = repository.Insert(entity);

                 return new AjaxResponse { Success = true, Result = insertResult };
             });

            return Json(result);
        }

        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public ActionResult Update(TopicUpdateInput model)
        {
            var result = BaseManager.Excute(repository =>
            {
                var isExists = repository.GetAll().AsNoTracking().Where(t => t.Name == model.Name && t.Id != model.Id).Any();

                if (isExists)
                    return new AjaxResponse { Success = false, Error = new ErrorInfo($"话题已存在:{model.Name}") };

                var old = repository.GetAll().AsNoTracking().FirstOrDefault(t => t.Id == model.Id);

                if (old == null)
                    return new AjaxResponse { Success = false, Error = new ErrorInfo($"话题不存在:{model.Name}") };

                old.InjectFrom(model);

                var updateResult = repository.Update(old);

                return new AjaxResponse { Success = true, Result = updateResult };
            });

            return Json(result);
        }

        /// <summary>
        /// 回收分区
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public ActionResult Recover(List<string> ids)
        {
            var result = this.BaseManager.Excute(rep =>
            {
                foreach (var id in ids)
                {
                    rep.Update(id, t => t.IsDeleted = true);
                }

                return new AjaxResponse();
            });
            return Json(result);
        }

        /// <summary>
        /// 话题选择（前端用）
        /// </summary>
        /// <returns></returns>
        public ActionResult Selection(string name = null)
        {
            var result = Reader.Query(query =>
            {
                query = query.Where(t => t.IsOnline == true);
                if (!string.IsNullOrEmpty(name))
                    query = query.Where(t => t.Name.Contains(name));

                var newQuery = query.OrderByDescending(s => s.Sort)
                                    .ThenByDescending(s => s.CreateAt)
                                    .Select(s => new NameValueDto
                                    {
                                        Name = s.Name,
                                        Value = s.Id
                                    })
                                    .AsQueryable();

                return newQuery;
            });

            return Json(result);
        }
    }
}
